package com.premedsidekick;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class Awards extends Activity {
	AwardsDatabaseAdapter dbHelper;
	AwardsCursorAdapter adapter;
	Cursor cursor;
	SharedPreferences preferences;
	Editor editor;
	
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.awards);
		dbHelper = new AwardsDatabaseAdapter(this);
		dbHelper.open();
		cursor = dbHelper.getAll();
		
		preferences = getSharedPreferences("user_settings", 0);
		editor = preferences.edit();
		int usages = preferences.getInt("usages", 0);
		
		ListView listview = (ListView)findViewById(R.id.awards_list_view);
		adapter = new AwardsCursorAdapter(this, cursor, dbHelper);
		listview.setAdapter(adapter);
		listview.setDivider(null);
		Button button = (Button)findViewById(R.id.awards_add);
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dbHelper.create("Insert award name");
				cursor.requery();
			}			
		});
		if (usages < 2) {
			final int state = usages + 1;
			Dialog dialog = new Dialog(this);
			dialog.setCancelable(true);
			dialog.setTitle("Basic Instructions");
			dialog.setContentView(R.layout.maindialog);
			TextView textview = (TextView)dialog.findViewById(R.id.TextView01);
			String message = getResources().getString(R.string.instructions);
			CharSequence sequence = Html.fromHtml(message);
			textview.setText(sequence);
			dialog.setOnCancelListener(new OnCancelListener() {

				@Override
				public void onCancel(DialogInterface dialog) {
					editor.putInt("usages", state);
					editor.commit();
				}
				
			});
			dialog.show();
		}
	}
	public void onDestroy() {
		super.onDestroy();
		cursor.close();
		dbHelper.close();
	}
	public class AwardsCursorAdapter extends CursorAdapter {
		Context context;
		View view;
		LayoutInflater inflater;
		AwardsDatabaseAdapter dbHelper;
		
		public AwardsCursorAdapter(Context context, Cursor cursor, AwardsDatabaseAdapter dbHelper) {
			super(context, cursor);
			this.context = context;
			this.dbHelper = dbHelper;
			inflater = LayoutInflater.from(context);
		}
		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			final Cursor c = cursor;
			view = inflater.inflate(R.layout.award_list, null);
			int id = cursor.getColumnIndex(dbHelper.KEY_ROWID);
			String key = cursor.getString(id);
			final int index = Integer.parseInt(key);
			
			int nameCol = cursor.getColumnIndex(dbHelper.KEY_NAME);
			String name = cursor.getString(nameCol);
			final EditText edittext = (EditText)view.findViewById(R.id.award_edittext);
			edittext.setText(name);
			
			edittext.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					edittext.selectAll();
				}
				
			});
			/*
			edittext.addTextChangedListener(new TextWatcher() {

				@Override
				public void afterTextChanged(Editable arg0) {
					dbHelper.update(index, edittext.getText().toString());
		        	//c.requery();
					
				}

				@Override
				public void beforeTextChanged(CharSequence arg0, int arg1,
						int arg2, int arg3) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onTextChanged(CharSequence arg0, int arg1,
						int arg2, int arg3) {
					// TODO Auto-generated method stub
					
				}
				
			});
			*/
			/*
			edittext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
		        @Override
		        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		            if (actionId == EditorInfo.IME_ACTION_DONE) {
		            	dbHelper.update(index, edittext.getText().toString());
			        	c.requery();
		                return true;
		            }
		            return false;
		        }
		    });
		    */
			/*
			edittext.setOnFocusChangeListener(new OnFocusChangeListener() {

				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					if (!hasFocus) {
						dbHelper.update(index, edittext.getText().toString());
						//c.requery();
					}
				}
				
			});
			*/
			
			edittext.setOnKeyListener(new OnKeyListener() {
			    public boolean onKey(View view, int keyCode, KeyEvent event) {
			        if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
			            (keyCode == KeyEvent.KEYCODE_ENTER)) {
			        	dbHelper.update(index, edittext.getText().toString());
			        	c.requery();
			        	return true;
			        }
			        return false;
			    }
			});
			
			view.setOnLongClickListener(new OnLongClickListener() {
				@Override
				public boolean onLongClick(View view) {
					AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
					builder.setMessage("Are you sure you want to delete this entry?")
					       .setCancelable(false)
					       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
					           public void onClick(DialogInterface dialog, int id) {
					                dbHelper.delete(index);
					                c.requery();
					           }
					       })
					       .setNegativeButton("No", new DialogInterface.OnClickListener() {
					           public void onClick(DialogInterface dialog, int id) {
					                dialog.cancel();
					           }
					       });
					AlertDialog alert = builder.create();
					alert.show();
					return true;
				}
	        });
			return view;
		}
		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			final Cursor c = cursor;
			
			int id = cursor.getColumnIndex(dbHelper.KEY_ROWID);
			String key = cursor.getString(id);
			final int index = Integer.parseInt(key);
			
			int nameCol = cursor.getColumnIndex(dbHelper.KEY_NAME);
			String name = cursor.getString(nameCol);
			final EditText edittext = (EditText)view.findViewById(R.id.award_edittext);
			edittext.setText(name);
			edittext.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					edittext.selectAll();
				}
				
			});
			/*
			edittext.addTextChangedListener(new TextWatcher() {

				@Override
				public void afterTextChanged(Editable arg0) {
					dbHelper.update(index, edittext.getText().toString());
		        	//c.requery();
					
				}

				@Override
				public void beforeTextChanged(CharSequence arg0, int arg1,
						int arg2, int arg3) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onTextChanged(CharSequence arg0, int arg1,
						int arg2, int arg3) {
					// TODO Auto-generated method stub
					
				}
				
			});
			*/
			/*
			edittext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
		        @Override
		        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		            if (actionId == EditorInfo.IME_ACTION_DONE) {
		            	dbHelper.update(index, edittext.getText().toString());
			        	c.requery();
		                return true;
		            }
		            return false;
		        }
		    });
		    */
		    /*
			edittext.setOnFocusChangeListener(new OnFocusChangeListener() {

				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					if (!hasFocus) {
						dbHelper.update(index, edittext.getText().toString());
						//c.requery();
					}
				}
				
			});
			*/
			
			edittext.setOnKeyListener(new OnKeyListener() {
			    public boolean onKey(View view, int keyCode, KeyEvent event) {
			        if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
			            (keyCode == KeyEvent.KEYCODE_ENTER)) {
			        	dbHelper.update(index, edittext.getText().toString());
			        	c.requery();
			        	return true;
			        }
			        return false;
			    }
			});
			
			view.setOnLongClickListener(new OnLongClickListener() {
				@Override
				public boolean onLongClick(View view) {
					AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
					builder.setMessage("Are you sure you want to delete this entry?")
					       .setCancelable(false)
					       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
					           public void onClick(DialogInterface dialog, int id) {
					                dbHelper.delete(index);
					                c.requery();
					           }
					       })
					       .setNegativeButton("No", new DialogInterface.OnClickListener() {
					           public void onClick(DialogInterface dialog, int id) {
					                dialog.cancel();
					           }
					       });
					AlertDialog alert = builder.create();
					alert.show();
					return true;
				}
	        });
		}

		
		
	}
	
	public class AwardsDatabaseAdapter {
		int DATABASE_VERSION = 1;
		String DATABASE_NAME = "awards_table";
		String KEY_ROWID = "_id";
		String KEY_NAME = "name";
		AwardsDatabaseHelper dbHelper;
		SQLiteDatabase database;
		Context context;
		ContentValues values;
		
		public AwardsDatabaseAdapter(Context context) {
			this.context = context;
		}
		public AwardsDatabaseAdapter open() throws SQLException {
			dbHelper = new AwardsDatabaseHelper(context);
			database = dbHelper.getWritableDatabase();
			return this;
			
		}
		public void close() {
			dbHelper.close();
		}
		
		public long create(String name) {
			values = new ContentValues();
			values.put(KEY_NAME, name);
			return database.insert(DATABASE_NAME, null, values);
		}
		public boolean update(long rowId, String name) {
			values = new ContentValues();
			values.put(KEY_NAME, name);
			return database.update(DATABASE_NAME, values, KEY_ROWID + "=" + rowId, null) > 0;
		}
		public boolean delete(long rowId) {
			return database.delete(DATABASE_NAME, KEY_ROWID + "=" + rowId, null) > 0;
		}
		public Cursor getAll() {
			Cursor cursor = database.query(DATABASE_NAME, new String[] {KEY_ROWID, KEY_NAME}, 
				null, null, null, null, null);
			if (cursor.getCount() == 0) {
				create("Insert award name");
				cursor = database.query(DATABASE_NAME, new String[] {KEY_ROWID, KEY_NAME}, 
					null, null, null, null, null);
			}
			return cursor;
		}
		
		public class AwardsDatabaseHelper extends SQLiteOpenHelper {
			AwardsDatabaseHelper(Context context) {
				super(context, DATABASE_NAME, null, DATABASE_VERSION);
			}

			@Override
			public void onCreate(SQLiteDatabase db) {
				db.execSQL("CREATE TABLE " + DATABASE_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
					KEY_NAME + " TEXT);");
				
			}

			@Override
			public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
				// TODO Auto-generated method stub
				
			}
		}
	}
	
}
